<template>
  <div class="home" ref="homeRef">
    <div class="home-top" v-if="isShowSearchBar">
      <search-bar @search-click="searchBarClick" />
    </div>
    <div class="nav-bar">
      <span class="title">JY旅途</span>
    </div>
    
    <div class="banner">
      <img src="@/assets/img/home/banner.webp" alt="">
    </div>

    <home-search-box />
    <home-categories />
    <home-house-list />

  </div>
</template>

<script>
  export default {name: "home"}
</script>
<script setup>
  import { watch, ref, computed, onActivated } from 'vue'
  import { useRouter } from 'vue-router'

  import HomeSearchBox from './cpns/home-search-box.vue'
  import HomeCategories from './cpns/home-categories.vue'
  import HomeHouseList from './cpns/home-house-list.vue'
  import SearchBar from '@/components/search-bar/search-bar.vue'

  import useHomeStore from "@/stores/modules/home"

  import useScroll from '@/hooks/useScroll'

  // 网络请求
  const HomeStore = useHomeStore()
  const { currentPage } = HomeStore
  HomeStore.fetchHotSuggestsData()
  HomeStore.fetchHomeCategories()
  HomeStore.fetchHouseList()

  // 监听window的滚动
  const homeRef = ref()
  const { isReachBottom, scrollTop } = useScroll(homeRef)
  watch(isReachBottom, (newValue) => {
    if (newValue) {
      HomeStore.fetchHouseList().then(res => {
        isReachBottom.value = false
      })
    }
  })

  // 搜索框显示的控制
  const isShowSearchBar = computed(() => {
    return scrollTop.value >= 350
  })

  // 跳转回home时，保留原来的位置
  onActivated(() => {
    homeRef.value?.scrollTo({
      top: scrollTop.value
    })
  })

  // searchbar跳转至搜索页面
  const router = useRouter()
  const searchBarClick = () => {
    router.push("/search")
  }
</script>

<style lang="less" scoped>
  .home {
    padding-bottom: 50px;
    height: 100vh;
    overflow-y: auto;
    box-sizing: border-box;
    background-color: #f7f8fB;
    
    .nav-bar {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 46px;

      border-bottom: solid 1px #f3f3f3;

      .title {
        color: var(--primary-color);
        font-weight: 700;
      }
    }

    .banner {
      img {
        width: 100%;
      }
    }

    .home-top {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      padding: 16px 16px 10px 16px;
      background-color: white;
      z-index: 100;
    }

  }
</style>